package api

import (
	"encoding/json"
	"fmt"
	"goProject/db"
	"goProject/public"
	"net/http"
	"strings"
	"time"
)

func Code(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	key := r.FormValue("key")
	if key == "" {
		w.Write([]byte("参数错误：key查询参数不存在"))
		return
	}
	result, err := db.Redis.Get(fmt.Sprint("code_", key)).Result()
	if err != nil {
		w.Write([]byte(codeHtmlNotFound))
		return
	}
	var rt public.SaveRedisContent
	err = json.Unmarshal([]byte(result), &rt)
	if err != nil {
		w.Write([]byte(fmt.Sprint("参数错误：json解码失败 ", err)))
		return
	}
	w.Write([]byte(fmt.Sprintf(codeHtmlContent, rt.Lang, rt.Exp-time.Now().Unix(), rt.Lang, htmlEscapeSequence2(rt.Content))))
}

func htmlEscapeSequence(content string) string {
	content = strings.ReplaceAll(content, `"`, "&quot;")
	content = strings.ReplaceAll(content, `&`, "&amp;")
	content = strings.ReplaceAll(content, `<`, "&lt;")
	content = strings.ReplaceAll(content, `>`, "&gt;")
	content = strings.ReplaceAll(content, ` `, "&nbsp;")
	return content
}
func htmlEscapeSequence2(content string) string {
	content = strings.ReplaceAll(content, `&`, "&amp;")
	content = strings.ReplaceAll(content, `<`, "&lt;")
	content = strings.ReplaceAll(content, `>`, "&gt;")
	return content
}

const codeHtmlContent = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1"><link href="https://ruige.fun/static/css/prism-plugins-1.29.0.css" rel="stylesheet"><script src="https://ruige.fun/static/js/prism-plugins-1.29.0.js"></script><script src="https://cdn.bootcdn.net/ajax/libs/prism/1.29.0/components/prism-%v.min.js"></script><title>查看代码_剩余【%v】秒</title><style>*{margin: 0;padding: 0;}</style></head><body><pre class="line-numbers" style="margin:0;overflow-y:hidden;font-size:0.85em;"><code class="language-%v">%v</code></pre></body></html>`

const codeHtmlNotFound = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1"><title>代码已过期</title></head><body><div style="font-size: 1.5em;">参数错误：key查询参数不存在或已过期；<br />您可以访问 <a href="/code">/code</a> 页面分享代码或者返回主页 <a href="/">主页</a>。</div></body></html>`
